class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
public class copyRandomList {
    public Node copyRandomList(Node head) {
        //深拷贝，通过创建新节点，两次遍历，第一次遍历创建新节点，第二次遍历连接新节点
        if(head == null) return null;//需要排除掉为空的情况
        Node cur = head;
        while (cur != null) {
            Node node = new Node(cur.val);
            node.next = cur.next;
            cur.next = node;
            cur = node.next;
        }
        cur = head;
        while (cur != null) {
            if (cur.random != null) {
                cur.next.random = cur.random.next;
            }
            cur = cur.next.next;
        }
        cur = head;
        Node newHead = head.next;
        while (cur != null) {
            Node node = cur.next;
            cur.next = node.next;
            cur = cur.next;
            if (cur != null) {
                node.next = cur.next;
            }
        }
        return newHead;
    }
}
